package ha.web.games_manager;

import ha.web.exceptions.GameException;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class GameM
 */
@WebServlet("/GameManager")
public class GameManager extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GameManager() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// player tries to end his turn - check move - if ok - change turn and give other player control
		
		
		//need to get: 
		//	current moves
		//  current player
//		//  player id		
//		if( ! request.getParameterMap().containsKey("user"))
//		{
//			System.out.println("OKOKOK");
//			out.print("");
//			return;
//		}
//		try{
			//check have user , moves
			GM ins = GM.getInstance();
			PrintWriter out = response.getWriter();	
			int userId = -1;
		      boolean cookieFound = false;
			  Cookie[] userCookie = request.getCookies();
			  for(int i=0; i<userCookie.length; i++) {
				  if ("chinese_checkers".equals(userCookie[i].getName())) {
			    	  String[] cookie = userCookie[i].getValue().split(":");
			    	  userId = Integer.parseInt(cookie[1]);
			    	  cookieFound = true;
				  }
			  }
			  if(!cookieFound)
				  return; //TODO
			if (request.getParameterMap().containsKey("my_turn")) {
				if (ins.get_game_id(userId)>0) {
					if (ins.my_turn(userId)){
						out.print(ins.getTable(userId)); 
						out.print("turn$"+ins.getTable(userId)); 
					}else{
						out.print("false");
						out.print("turn$false");
					}
				}
				
				return;
			}
			
			if (request.getParameterMap().containsKey("chat") ) {
				//handle chat request:
				String newLine= request.getParameter("chat");
				
				ins.add_line_to_chat(userId, newLine);
				out.print(ins.get_chat(userId));
				out.print("chat$"+ins.get_chat(userId));
							
				return;
			}
			/*
			if (request.getParameterMap().containsKey("boardUp") ){
					
				out.print(ins.getTable(userId));
				return;
			}
			*/
			if (request.getParameterMap().containsKey("in_game") )
			{
				
				if (ins.get_game_id(userId)>0)
				{
					out.print("true");
					return;

				}else{
					out.print("current game: ");
					out.print(ins.get_game_id(userId));
					out.print(" user is " + ins.getPlayerById(userId).getName());
					return;
				}
			}
			if (request.getParameterMap().containsKey("moves") )
			{
				//handle move request
				String moves= request.getParameter("moves");
				//return new board:
				//if (ins.validate_player_move(move, gameId, who_moved)) ;
				//TODO:  call validate player with right variables & finish validate move
				try {
					ins.setLastMove(userId, moves);
				} catch (GameException e) {
					out.print("move$not_valid$"+e.getMessage()+"$"+ins.getTable(userId));
					return;
				}
				ins.switch_turn(ins.get_game_id(userId));
//				out.print("user is " + userName + " moves are" + moves );
				out.print("turn_end");
				out.print("move$turn_end$"+ins.getTable(userId));
				
				return;
			}
		}
//		finally
//		{
//			out.print("");
//		}	
	
}

	
	
//}


